package com.ly.friend.manager.exam;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.common.core.constants.CacheConstants;
import com.ly.common.core.constants.Constants;
import com.github.pagehelper.PageHelper;
import com.ly.common.core.enums.ExamListType;
import com.ly.common.core.enums.ResultCode;
import com.ly.common.security.exception.ServiceException;
import com.ly.friend.domain.exam.Exam;
import com.ly.friend.domain.exam.ExamQuestion;
import com.ly.friend.domain.exam.dto.ExamQueryDTO;
import com.ly.friend.domain.exam.vo.ExamVO;
import com.ly.friend.domain.user.UserExam;
import com.ly.friend.mapper.exam.ExamMapper;
import com.ly.friend.mapper.exam.ExamQuestionMapper;
import com.ly.friend.mapper.user.UserExamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import com.ly.common.redis.service.RedisService;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class ExamCacheManager {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    public Long getListSize(Integer examListType,Long userId) {
        String examListKey = getExamListKey(examListType,userId);
        return redisService.getListSize(examListKey);
    }

    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }


    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
//        计算分页范围 pageNum: 当前页码（从1开始) -1:页码从1开始，但索引从0开始
//        pageSize: 每页显示的记录数 如果要获取10条记录，需要从start到start+9
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
//        Redis的LRANGE命令使用的是闭区间
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
//        从Redis获取考试ID列表：
        String examListKey = getExamListKey(examQueryDTO.getType(),userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
//        组装VO对象：
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
//        缓存回源机制：
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            examVOList = getExamListByDB(examQueryDTO,userId); //从数据库中获取数据
            //同步缓存
            refreshCache(examQueryDTO.getType(),userId);
        }
        return examVOList;
    }

    public List<Long> getAllUserExamList(Long userId){
//        构造Redis缓存key:
        String examListKey =CacheConstants.USER_EXAM_LIST+userId;
//        尝试从Redis获取缓存数据:
//        如果缓存中有数据，返回缓存数据
        List<Long> userExamIdList = redisService.getCacheListByRange(examListKey, 0, -1, Long.class);
        if(CollectionUtil.isNotEmpty(userExamIdList)){
            return userExamIdList;
        }
//        缓存未命中时查询数据库:
        List<UserExam> userExamList =
                userExamMapper.selectList(new LambdaQueryWrapper<UserExam>().eq(UserExam::getUserId, userId));
        if (CollectionUtil.isEmpty(userExamList)){
            return null;
        }
//        刷新缓存逻辑
        refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
        return userExamList.stream().map(UserExam::getExamId).collect(Collectors.toList());
    }
    public void addUserExamCache(Long userId, Long examId) {
        String userExamListKey = getUserExamListKey(userId);
        redisService.leftPushForList(userExamListKey, examId);
    }



    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId), 0, Long.class);
    }

    public Long preQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index - 1, Long.class);

    }

    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        long lastIndex = getExamQuestionListSize(examId) - 1;
        if (index == lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index + 1, Long.class);

    }

    //刷新缓存逻辑
    public void refreshCache(Integer examListType , Long userId) {
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
//            查询未完赛的竞赛列表
//            查询 endTime > 当前时间 且状态为启用（status = Constants.TRUE）的考试，
//            按创建时间降序排列。
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
//            历史考试（EXAM_HISTORY_LIST）
//            查询历史竞赛
//            查询 endTime ≤ 当前时间 且状态为启用的考试，同样按创建时间降序排列。
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
//            用户参与的考试（USER_EXAM_LIST）
//            通过 userExamMapper.selectUserExamList(userId) 获取用户关联的考试列表，
//            并将 ExamVO 转换为 Exam 对象。
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            examList=BeanUtil.copyToList(examVOList,Exam.class);
        }

        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

//      将一个考试列表 (examList) 转换为两种不同的数据结构
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
//            getDetailKey(exam.getExamId()) 生成的考试详情缓存键 exam 完整的 Exam 对象
            examMap.put(getDetailKey(exam.getExamId()), exam);
//            存储所有考试的 ID (exam.getExamId())
            examIdList.add(exam.getExamId());
        }
        //multiSet批量的将数据存入到缓存中
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType,userId));
        redisService.rightPushAll(getExamListKey(examListType,userId), examIdList);      //刷新列表缓存
    }

    public void refreshExamQuestionCache(Long examId) {
//        使用 MyBatis-Plus 的 LambdaQueryWrapper 查询指定 examId 的所有考题
//        只选择 questionId 字段
//        按 examQuestionId 升序排序
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getExamQuestionId));
        if(CollectionUtil.isEmpty(examQuestionList)){
            return;
        }
//        将 questionId 集合转换为 List 有序排列
        List<Long> examQuestionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).collect(Collectors.toList());
//        使用 Redis 的 rightPushAll 方法将整个集合存入列表
        redisService.rightPushAll(getExamQuestionListKey(examId),examQuestionIdList);
        //节省redis缓存资源,设置redis删除时间,当竞赛结束,就释放
        Long seconds= ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0));
        redisService.expire(getExamQuestionListKey(examId),seconds, TimeUnit.SECONDS);
    }

    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO,Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if (ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())){
            //查询我的竞赛列表
            userExamMapper.selectUserExamList(userId);
        }else{
             //查询C端的竞赛列表
            return examMapper.selectExamList(examQueryDTO);
        }
        return null;
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
             detailKeyList.add(getDetailKey(examId));
        }
        //multiGet拿到数据
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
       //把所有null元素清掉（可能某些key在Redis中不存在）
        CollUtil.removeNull(examVOList);
//        检查最终结果是否为空||检查结果数量是否与原始ID列表数量一致
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    private String getExamListKey(Integer examListType,Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            return CacheConstants.USER_EXAM_LIST+userId;
        }
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }

    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }
   
}